package com.apes.scm.sal.guideOrder;

import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.ApesConst;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = GuideOrder.CONST_TABLE_NAME)
public class GuideOrder extends Model {

    public static final String CONST_TABLE_NAME = "Guide_Order";

    @Id
    @Column(name = "id")
    @Comment("导购单号")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "导购单", prefix = "2")
    private String id;

    @Comment("公司")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    private PartyRole company;

    @Comment("部门")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    private Dept dept;

    @Column(name = "amt_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("税金")
    private double amtTax = 0;

    @Column(name = "amt_untaxed", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("不含税金额")
    private double amtUntaxed = 0;

    @Column(name = "amt_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计")
    private double amtTotal = 0;

    @Column(name = "state", length = 10, nullable = false)
    private String state = "sent";

    @Comment("源单据")
    @Column(name = "origin", length = 30)
    private String origin;

    @Comment("订单备注")
    @Column(name = "remark", length = 120)
    private String remark;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveUID; //审核

    @Comment("审批日期")
    @Column(name = "date_approve")
    private Date dateApprove;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<GuideOrderItem> guideItems = new HashSet(); //订单行

    public Set<GuideOrderItem> getSaleItems() {
        for (GuideOrderItem item : guideItems) {
            // 去除数量为 0 的行
            if (item.getProductUomQty() == 0) {
                guideItems.remove(item);
                continue;
            }
            item.setOrder(this);
            item.setCompany(this.company);
        }
        return guideItems;
    }
}
